import React, { useEffect, useState } from 'react';
import router from 'umi/router';
import {
  Table, Modal, Form, Input, Col, message, Select, DatePicker, Row, Button,
} from 'antd';
import moment from 'moment'
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import RenderButtom from '@/components/RenderButton';
import SearchBox from '@/components/SearchBox'
import {
  fetchCollectionWay,
  deleteCollectionWay,
  saveCollectionWay,
  addCollectionWay,
} from '@/services/rentCenter/collection';
import { connect } from 'dva';
import { formItemLayout } from '@/utils/utils';

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { Option } = Select
const { TextArea } = Input
const stats = ['未收', '待确认', '部分已收', '全部已收']
const statsList = [
  {
    label: '未收',
    value: '0',
  },
  {
    label: '部分已收',
    value: '2',
  },
  {
    label: '全部已收',
    value: '3',
  },
]
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    align: 'center',
    key: 'index',
  },
  {
    title: '结算单号',
    align: 'center',
    key: 'settlementCode',
  },
  {
    title: '合同编号',
    align: 'center',
    key: 'contractNum',
  },
  {
    title: '款项类型',
    align: 'center',
    key: 'fundType',
  },
  {
    title: '金额（元）',
    align: 'center',
    key: 'sumMoney',
  },
  {
    title: '应收金额（元）',
    align: 'center',
    key: 'receivableMoney',
  },
  {
    title: '已收金额（元）',
    align: 'center',
    key: 'getMoney',
  },
  {
    title: '款项周期',
    align: 'center',
    key: 'moneyCycle',
  },
  {
    title: '计划收款日期',
    align: 'center',
    key: 'planDate',
  },
  {
    title: '状态',
    key: 'status',
    render: params => (
      <span>{stats[params.status]}</span>
    ),
  },
];

const receivingListing = props => {
  const { getFieldDecorator } = props.form;
  const [data, setColData] = useState([]);
  const [data2, setColData2] = useState([
    {
      receiveType: null, // 收款方式
      payee: null, // 催收人
      getMoney: null, // 已收金额
      receiveDate: null, // 收款日期
      voucherImg: null,
      status: '0',
      payeeNum: null,
      voucherNum: null,
      note: null,
      index: 0,
    },
  ]);
  const [record, setRecord] = useState([]);
  const [planDate, setplanDate] = useState(null);
  const [collectionWays, setcollectionWays] = useState([]);
  const [staffList, setstaffList] = useState([]);
  const [collectionList, setcollectionList] = useState([]);
  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
  });
  const [info, setInfo] = useState({
    status: 1,
  });
  // 分配\新增角色模态框
  const [isShow, setState] = useState(false);

  // 列表
  const getList = async params => {
    const r = await fetchCollectionWay(params);
    if (r.data && r.data.data) {
      setColData(r.data.data);
    }
  };
  useEffect(() => {
    getList(listQuery);
  }, [listQuery]);

  // 查询
  const searchOneBtn = async params => {
    getList(params);
  };
  // 新增/修改 模态框
  const handleStatus = record => {
    setState(!isShow);
    if (record) {
      setInfo(record)
    }
  };
  const time1 = (v, t) => {
    setplanDate(v)
    setListQuery({ ...listQuery, planDate: t })
  };
  // 查询表单
  const getFields = () => (
    <Col span={18}>
      <Col span={8}>
        <Form.Item label="合同编号">
          <Input onChange={v => { setListQuery({ ...listQuery, contractNum: v.target.value }) }} placeholder="请输入合同编号" value={listQuery.contractNum} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="结算单号">
          <Input onChange={v => { setListQuery({ ...listQuery, settlementCode: v.target.value }) }} placeholder="请输入结算单号" value={listQuery.settlementCode} />
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="状态">
          <Select value={listQuery.status} onChange={v => { setListQuery({ ...listQuery, status: v }) }} placeholder="选择状态">
            { statsList.map((v, i) => (<Option key={v.value}>{v.label}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="款项类型">
          <Select value={listQuery.fundType} onChange={v => { setListQuery({ ...listQuery, fundType: v }) }} placeholder="选择款项类型">
            { collectionList.map((v, i) => (<Option key={v.value}>{v.label}</Option>)) }
          </Select>
        </Form.Item>
      </Col>
      <Col span={8}>
        <Form.Item label="计划收款日期">
          <DatePicker className="width100" value={planDate} placeholder="请选择计划收款日期" onChange={time1} />
        </Form.Item>
      </Col>
    </Col>
  );
  // 查询表单逻辑
  const handleSearch = e => {
    e.preventDefault()
    searchOneBtn(listQuery);
  };

  const removeRole = async record => {
    deleteCollectionWay({
      id: record.id,
    }).then(res => {
      if (res.data && res.data.code === '0') {
        const index = data.findIndex(e => e.id === record.id);
        setColData(() => {
          data.splice(index, 1);
          return [...data];
        });
      }
    })
  };
  // 表单提交
  const handleSubmit = e => {
    e.preventDefault();
    props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (values.id) {
          saveCollectionWay(values).then(() => {
            getList(listQuery)
            setState(!isShow);
          })
        } else {
          addCollectionWay(values).then(() => {
            getList(listQuery)
            setState(!isShow);
          })
        }
      }
    });
  };
  // 清空查询条件
  const handleReset = () => {
    const aobj = {
      pageNo: 1,
      pageSize: 10,
    }
    setplanDate('')
    setListQuery(aobj)
    getList(aobj)
  };
  // 按钮逻辑
  const handleBtn = type => {
    if (record.length !== 1 && type !== 1) return message.warning('请勾选一条数据！');
    switch (type) {
      // 新增
      case 1:
        return handleStatus();
      // 查询
      case 2:
        return handleSearch();
      case 3:
        return handleStatus(record[0]);
      case 4:
        return removeRole(record[0]);
      case 5:
        router.push({ pathname: '/rentCenter/contractManage/contractDetail', query: { i: record[0].id } });
        break
      default:
        return ''
    }
  };
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setRecord(selectedRows)
    },
  };
  const addReceiving = () => {
    console.log('add')
    const arr = data2.map((v, i) => ({
        ...v,
        index: i,
      }))
    arr.push({
      receiveType: null, // 收款方式
      payee: null, // 催收人
      getMoney: null, // 已收金额
      receiveDate: null, // 收款日期
      voucherImg: null,
      status: '0',
      payeeNum: null,
      voucherNum: null,
      note: null,
      index: data2.length,
    })
    setColData2(arr)
  };
  const columns2 = [
    {
      title: '序号',
      dataIndex: 'index',
      align: 'center',
      key: 'index',
    },
    {
      title: '收款日期',
      align: 'center',
      key: 'receiveDate',
      render: (v, r, i) => (
        <DatePicker value={v.receiveDate ? moment(v.receiveDate) : null} onChange={(v2, t) => {
          data2[i].receiveDate = t
          setColData2([...data2])
        }} />
      ),
    },
    {
      title: '收款方式',
      align: 'center',
      key: 'receiveType',
      render: (v, r, i) => (
        <><Select value={r.receiveType} className="width100" onChange={v2 => {
          data2[i].receiveType = v2
          setColData2([...data2])
        }}>
          { collectionWays.map(vl => (<Option key={vl.id}>{vl.receiveName}</Option>)) }
        </Select></>
      ),
    },
    {
      title: '已收金额（元）',
      align: 'center',
      key: 'getMoney',
      render: (v, r, i) => (
        <Input value={r.getMoney} onChange={v2 => {
          data2[i].getMoney = v2.target.value
          setColData2([...data2])
        }} />
      ),
    },
    {
      title: '催收人',
      align: 'center',
      key: 'payeeNum',
      render: (v, r, i) => (
        <><Select value={r.payeeNum} className="width100" onChange={v2 => {
          data2[i].payeeNum = v2
          setColData2([...data2])
        }}>
          { staffList.map(vl => (<Option key={vl.id}>{vl.name}</Option>)) }
        </Select></>
      ),
    },
    {
      title: '收据单号',
      align: 'center',
      key: 'voucherNum',
      render: (v, r, i) => (
        <Input value={r.voucherNum} onChange={v2 => {
          data2[i].voucherNum = v2.target.value
          setColData2([...data2])
        }} />
      ),
    },
    {
      title: '备注',
      align: 'center',
      key: 'notes',
      render: (v, r, i) => (
        <Input value={r.notes} onChange={v2 => {
          data2[i].notes = v2.target.value
          setColData2([...data2])
        }} />
      ),
    },
    {
      title: '操作人',
      align: 'center',
      key: 'operator',
    },
    {
      title: '操作',
      align: 'center',
      key: 'id',
      render: (v, r, i) => (<Button type="danger" onClick={() => {
        data2.splice(i, 1)
        const arr2 = data2.map((v2, i2) => ({
            ...v2,
            index: i2,
          }))
        setColData2(arr2)
      }}>删除</Button>),
      // render: (v, r, i) => { data2[i].id ? (<Button type="danger" onClick={() => {
      //       data2.splice(i, 1)
      //       setColData2([...data2])
      //     }}>删除</Button>) : null },
    },
  ];
  return (
    <PageHeaderWrapper>
      {/* 查询条件 */}
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table columns={columns} dataSource={hasSearchBtn ? data : data} rowSelection={rowSelection} rowKey={record => record.id} />
      {/* 新增/修改 */}
      <Modal
        title="收款信息"
        visible={isShow}
        style={{ top: '10%' }}
        width="90%"
        onOk={handleSubmit.bind(this)}
        onCancel={handleStatus.bind(this)}
        destroyOnClose
      >
        <div className="abox">
          <p>基本信息</p>
          <Form {...formItemLayout}>
            <Row>
              <Col span={12}>
                <Form.Item label="结算单号">
                  {getFieldDecorator('settlementCode', {
                    initialValue: info.settlementCode,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="合同编号">
                  {getFieldDecorator('contractNum', {
                    initialValue: info.contractNum,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="商户名称">
                  {getFieldDecorator('merchantsName', {
                    initialValue: info.merchantsName,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="商户编号">
                  {getFieldDecorator('merchantsNumber', {
                    initialValue: info.merchantsNumber,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="款项类型">
                  {getFieldDecorator('fundType', {
                    initialValue: info.fundType,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="款项周期">
                  {getFieldDecorator('moneyCycle', {
                    initialValue: info.moneyCycle,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="金额（元）">
                  {getFieldDecorator('sumMoney', {
                    initialValue: info.sumMoney,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="应收金额（元）">
                  {getFieldDecorator('receivableMoney', {
                    initialValue: info.receivableMoney,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="已收金额（元）">
                  {getFieldDecorator('getMoney', {
                    initialValue: info.getMoney,
                  })(<Input />)}
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="计划收款日期">
                  {getFieldDecorator('planDate', {
                    initialValue: info.planDate,
                  })(<Input />)}
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div className="abox">
          <p className="marginB20">收款信息</p>
          <Button type="primary" onClick={addReceiving}>添加收款</Button>
          <Table columns={columns2} dataSource={data2} rowKey="index" />
        </div>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default connect(({ role, global }) => ({
  role,
  hasSearchBtn: global.hasSearchBtn,
}))(Form.create()(receivingListing));
